package cn.com.zcode.auth.control;

import java.text.MessageFormat;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;

import cn.com.zcode.auth.model.Resource;
import cn.com.zcode.auth.service.AuthService;

public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section> {
	private static Logger logger = Logger.getLogger(ChainDefinitionSectionMetaSource.class);
	private AuthService authService;

	private String filterChainDefinitions;

	public Section getObject() throws BeansException {
		Ini ini = new Ini();
		ini.load(filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		return section;
	}

	public Class<?> getObjectType() {
		return this.getClass();
	}

	public boolean isSingleton() {
		return false;
	}

	public void setFilterChainDefinitions(String filterChainDefinitions) {

		List<Resource> list = authService.findAllResource();

		StringBuffer filter = new StringBuffer(filterChainDefinitions);
		logger.info("===========Init Permission Resources Beginning===========");
		for (Resource permission : list) {
			logger.info(permission);
			String url = permission.getUrl();
			if (!StringUtils.isEmpty(url)) {
				String code = permission.getCode();
				String type = permission.getAuthType();
				filter.append("/");
				filter.append(url.trim());
				filter.append(" = " + type + ",");
				filter.append(MessageFormat.format("perms[\"{0}\"]", code));
				filter.append("\n");
			}
		}
		logger.info("===========Init Permission Resources End===========");
		
		logger.info(filter);
		this.filterChainDefinitions = filter.toString();
	}

	public String getFilterChainDefinitions() {
		return filterChainDefinitions;
	}

	public AuthService getAuthService() {
		return authService;
	}

	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

	 
}